// pages/play/play.js
var interval;
var varName;
var ctx = wx.createCanvasContext('canvasArcCir');

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    loadshow: 'block',
    loadplayershow: 'block',
    x: -129,
    xx: wx.getSystemInfoSync().windowWidth * 2,
    moveablewidth: (wx.getSystemInfoSync().windowWidth * 2) + "px",
    countdown: 10,
    canvasshow: "none",
    playPage: "none",
    endplay: "none",
    playmessage: {},
    palyer: {},
    startTime: 0, // 每轮pk开始的时间
    you: 0, // 当前用户的成绩
    opponent: 0, // 对手的成绩
    youTotal: 0,
    opponentTotal: 0,
    round: 0, // 第几回合
    youStatus: 0, // 当前用户是否完成答题
    opponentStatus: 0, // 对手是否完成答题
    disabledButton: false,
    jushaTop: '100rpx',
    jueshaLeft: '317rpx',
    jieshuImg: 'http://www.okaoyan.com/app/chaojiwangzhe/images/jieshu/success.png',
    result: {},
    winurl: "http://www.okaoyan.com/app/chaojiwangzhe/images/jieshu/win.png",
    leftClass: 'user-left-juesha',
    rightClass: 'user-right-juesha',
    id: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var id = options.id;
    this.setData({
      id: id
    })

    // console.log(app.globalData.userInfo);
    if (app.globalData.userInfo) {

      this.setData({
        userInfo: app.globalData.userInfo
      })

      console.log(app.globalData.userInfo);
    }
    else {
      app.userInfoReadyCallback = res => {
        console.log(res);
        that.setData({
          userInfo: app.globalData.userInfo
        })
      }
    }

    var socketOpen = false;
    var socketMsgQueue = [];

    // 连接socket
    wx.connectSocket({
      url: 'wss://miniapp.okaoyan.com/cable?session_key=' + encodeURIComponent(wx.getStorageSync('code_secret_key'))
    })

    wx.onSocketOpen(function (res) {
      socketOpen = true;
      console.log('WebSocket连接已打开！');

      // 订阅消息
      wx.sendSocketMessage({
        data: JSON.stringify({
          command: 'subscribe',
          identifier: JSON.stringify({
            channel: 'MatchChannel',
          })
        }),
        success(res) {
          console.log("订阅成功", res);
          
        },
        fail() {

        }
      })
    })

    // 订阅成功，加载对手
    wx.onSocketMessage(function (res) {

      var data = JSON.parse(res.data);
      console.log("onsocket", data);
      console.log("data.message", data.message);

      // if (data.message && data.message.result == -1) {
      //   console.log('111');
      //   wx.showModal({
      //     title: '提示',
      //     content: '入场金币不足',
      //     success (res) {
      //       console.log(res);
      //     }
      //   })
      //   return;
      // }
      if (data.message) {
        if (data.message.type) {
          if (data.message.type == "match_response") {
            if (parseInt(data.message.code) == 1018) {
              wx.closeSocket({
                success() {
                  console.log("用户退出");
                }
              })

              clearInterval(varName);
              
              wx.showModal({
                title: '提示',
                content: '入场金币不足',
                showCancel: false,
                success (res) {
                  console.log(res);
                  wx.navigateBack({
                    delta: 1
                  })
                }
              })

              return;
            }
          }
        }
      }

      if (data.type == 'confirm_subscription') {
        console.log('加载对手');
        that.initPlayer();
      }

      if (data.message) {
        console.log("data.message", data.message);
        if (data.message.type) {
          console.log("data.message.type", data.message.type);

          // 匹配对手处理
          if (data.message.type == 'match_response') {
            // 对手匹配成功
            console.log("对手匹配成功");
            that.setData({
              palyer: data.message,
              loadshow: 'none',
              loadplayershow: 'block'
            })

            console.log("第一次获取题目：", that.data.round);
            // 获取题目
            wx.sendSocketMessage({
              data: JSON.stringify({
                command: 'message',
                identifier: JSON.stringify({
                  channel: 'MatchChannel',
                }),
                data: JSON.stringify({
                  action: 'get_question',
                  index: that.data.round
                })
              }),
              success(res) {
                console.log('获取题目成功');
              },
              fail(res) {

              }
            })
          }
          // 获取题目处理
          if (data.message.type == 'get_question_response') {

            setTimeout(function () {
              that.setData({
                playmessage: data.message,
                loadplayershow: 'none',
                playPage: "block",
                canvasshow: "block",
                round: that.data.round + 1,
                startTime: Date.parse(new Date()) / 1000
              })
            }, 500);

            that.drawCircle();
          }
        }

        // 回合结束，处理分数
        if (data.message.type == 'submit_result_response') {
          that.setData({
            disabledButton: false
          })
          if (data.message.role == 'you') {
            that.setData({
              you: parseInt(data.message.score, 10) + parseInt(that.data.you, 10),
              youStatus: 1
            })
          } else {
            that.setData({
              opponent: parseInt(data.message.score, 10) + parseInt(that.data.opponent, 10),
              opponentStatus: 1
            })
          }

          // 进入下个回合
          if (that.data.youStatus == 1 && that.data.opponentStatus == 1) {

            that.setData({
              youStatus: 0,
              opponentStatus: 0
            })

            console.log("当前第X回合", that.data.round);
            // 
            if (that.data.round == 5) {
              
              clearInterval(varName);
              
              wx.sendSocketMessage({
                data: JSON.stringify({
                  command: 'message',
                  identifier: JSON.stringify({
                    channel: 'MatchChannel',
                  }),
                  data: JSON.stringify({
                    action: 'judge'
                  })
                }),
                success(res) {
                  console.log(res);
                  
                }
              })
            }
            // 获取题目
            wx.sendSocketMessage({
              data: JSON.stringify({
                command: 'message',
                identifier: JSON.stringify({
                  channel: 'MatchChannel',
                }),
                data: JSON.stringify({
                  action: 'get_question',
                  index: that.data.round
                })
              }),
              success(res) {
                console.log('获取题目成功');
                console.log(res);
              },
              fail(res) {

              }
            })
          }
        }

        // pk结果
        if (data.message.type == 'judge_response') {

          wx.closeSocket({
            success() {
              console.log("用户退出");
            }
          })

          that.setData({
            endplay: 'block',
            playPage: 'none'
          })
          
          // data.message.result = 1;
          if (parseInt(data.message.result, 10) == 0) {
            that.setData({
              jieshuImg: 'http://www.okaoyan.com/app/chaojiwangzhe/images/jieshu/ping.png',
              jushaTop: '100rpx',
              jueshaLeft: '320rpx',
              winurl: 'http://www.okaoyan.com/app/chaojiwangzhe/images/jieshu/pinju.png',
              leftClass: 'user-left-ping',
              rightClass: 'user-right-juesha'
            })
          } else if (parseInt(data.message.result, 10) == 1) {
            that.setData({
              jieshuImg: 'http://www.okaoyan.com/app/chaojiwangzhe/images/jieshu/success.png',
              jushaTop: '100rpx',
              jueshaLeft: '317rpx'
            })
          }else {
            that.setData({
              jieshuImg: 'http://www.okaoyan.com/app/chaojiwangzhe/images/jieshu/fail.png',
              jushaTop: '50rpx',
              jueshaLeft: '340rpx',
              leftClass: 'user-left-fail',
              rightClass: 'user-right-fail'
            })
          }
          that.setData({
            result: data.message
          });
        }
      }
      // 判断用户信息
    })
    
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败，请检查！');
    })
  },
  initPlayer: function () {

    var that = this;
    // 匹配对手
    wx.sendSocketMessage({
      data: JSON.stringify({
        command: 'message',
        identifier: JSON.stringify({
          channel: 'MatchChannel',
        }),
        data: JSON.stringify({
          action: 'match',
          level: that.data.id
        })
      }),
      success(res) {
        // 匹配成功，展示
        console.log('匹配对手成功');
      }
    })
  },

  login: function () {
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res);
        wx.request({
          url: "https://miniapp.okaoyan.com/api/v1/login/get_secret_key",
          data: {
            code: res.code
          },
          success(res) {
            console.log(res);
            console.log(res.data.data.session_key);
            wx.setStorage({
              key: 'code_secret_key',
              data: res.data.data.session_key,
            })
          }
        })
      }
    })
  },
  submitResult (e) {
    var id = e.currentTarget.dataset.id;
    var that = this;

    this.setData({
      disabledButton: true
    })
    
    if (that.data.round == 5) {

      wx.sendSocketMessage({
        data: JSON.stringify({
          command: 'message',
          identifier: JSON.stringify({
            channel: 'MatchChannel',
          }),
          data: JSON.stringify({
            action: 'judge',
            level: that.data.id
          })
        }),
        success(res) {
          console.log(res);
        }
      })

      return;
    }

    wx.sendSocketMessage({
      data: JSON.stringify({
        command: 'message',
        identifier: JSON.stringify({
          channel: 'MatchChannel',
        }),
        data: JSON.stringify({
          action: 'submit_result',
          question_id: that.data.playmessage.id,
          answer: parseInt(id,10),
          begin_time: that.data.startTime,
          end_time: Date.parse(new Date()) / 1000
        })
      }),
      success (res) {
        console.log("题目提交成功！");
      }
    })
  },

  drawCircle: function () {
    clearInterval(varName);
    function drawArc(s, e) {
      ctx.setFillStyle('#ffffff');
      ctx.clearRect(0, 0, 50, 50);
      ctx.draw();
      var x = 25, y = 25, radius = 22;
      ctx.setLineWidth(5);
      ctx.setStrokeStyle('#14b8ff');
      ctx.setLineCap('round');
      ctx.beginPath();
      ctx.arc(x, y, radius, s, e, false);
      ctx.stroke()
      ctx.draw()
    }
    var step = 1, startAngle = 1.5 * Math.PI, endAngle = 0;
    var animation_interval = 1000, n = 10;
    var that = this;
    var animation = function () {
      if (step <= n) {
        endAngle = step * 2 * Math.PI / n + 1.5 * Math.PI;
        drawArc(startAngle, endAngle);
        that.setData({
          countdown: 10 - step
        })
        step++;
      } else {
        console.log("结束一轮答题");
        // 获取题目，并判断对手是否答完题
        wx.sendSocketMessage({
          data: JSON.stringify({
            command: 'message',
            identifier: JSON.stringify({
              channel: 'MatchChannel',
            }),
            data: JSON.stringify({
              action: 'submit_result',
              question_id: that.data.playmessage.id,
              answer: -1,
              begin_time: that.data.startTime,
              end_time: Date.parse(new Date()) / 1000
            })
          }),
          success(res) {
            console.log("题目提交成功！");
          }
        })

        clearInterval(varName);
      }
    };
    varName = setInterval(animation, animation_interval);
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //创建并返回绘图上下文context对象。
    var cxt_arc = wx.createCanvasContext('canvasCircle');
    cxt_arc.setLineWidth(6);
    cxt_arc.setStrokeStyle('#eaeaea');
    cxt_arc.setLineCap('round');
    cxt_arc.beginPath();
    cxt_arc.arc(25, 25, 22, 0, 2 * Math.PI, false);
    cxt_arc.stroke();
    cxt_arc.draw();
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(varName);
    wx.closeSocket({
      success() {
        console.log("用户退出");
      }
    })
  }
})